/*
 * Copyright (C) 2016 Nishant Srivastava
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package github.nisrulz.easydeviceinfo.base;

import ohos.aafwk.ability.Ability;
import ohos.app.Context;
import ohos.biometrics.authentication.BiometricAuthentication;
import ohos.security.SystemPermission;
import ohos.security.permission.NeedsPermission;

import java.util.Optional;

/**
 * The type Easy fingerprint mod.
 *
 * @since 2021-06-10
 */
public class EasyFingerprintMod {
    private Optional<BiometricAuthentication> fingerprintManager = null;
    private Context c;
    private static final int defaultRetChkAuthAvb = -1;

    /**
     * Instantiates a new Easy fingerprint mod.
     * <p>
     * You need to declare the below permission in the manifest file to use this properly
     * <p>
     * SystemPermission.ACCESS_BIOMETRIC
     *
     * @param context the context
     */

    @NeedsPermission(SystemPermission.ACCESS_BIOMETRIC)
    public EasyFingerprintMod(final Ability context) {
        c = context;
        if (PermissionUtil.hasPermission(context, SystemPermission.ACCESS_BIOMETRIC)) {
            try {
                fingerprintManager = Optional.ofNullable(BiometricAuthentication.getInstance(context));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * Is fingerprint sensor present boolean.
     * <p>
     * You need to declare the below permission in the manifest file to use this properly
     * <p>
     * SystemPermission.ACCESS_BIOMETRIC
     *
     * @return the boolean
     */
    @NeedsPermission(SystemPermission.ACCESS_BIOMETRIC)
    public final boolean isFingerprintSensorPresent() {
        if (PermissionUtil.hasPermission(c, SystemPermission.ACCESS_BIOMETRIC)) {
            int retChkAuthAvb = fingerprintManager.isPresent() ? fingerprintManager.get().checkAuthenticationAvailability(
                BiometricAuthentication.AuthType.AUTH_TYPE_BIOMETRIC_FINGERPRINT_ONLY,
                BiometricAuthentication.SecureLevel.SECURE_LEVEL_S2, true) : defaultRetChkAuthAvb;
            return retChkAuthAvb != BiometricAuthentication.BA_CHECK_AUTH_TYPE_NOT_SUPPORT;
        }
        return false;
    }
}
